package web

import (
	"encoding/json"
	"io"
	"net/http"
)

// 文件服务器API处理器 - 获取配置
func FileServerGetConfigHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	
	response := struct {
		Success bool             `json:"success"`
		Message string           `json:"message,omitempty"`
		Data    *FileServerConfig `json:"data,omitempty"`
	}{
		Success: true,
		Data:    GetFileServerConfig(),
	}
	
	json.NewEncoder(w).Encode(response)
}

// 文件服务器API处理器 - 更新配置
func FileServerUpdateConfigHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	
	// 读取请求体
	body, err := io.ReadAll(r.Body)
	if err != nil {
		errorResponse(w, "读取请求数据失败: "+err.Error(), http.StatusBadRequest)
		return
	}
	
	// 解析JSON
	var newConfig FileServerConfig
	if err := json.Unmarshal(body, &newConfig); err != nil {
		errorResponse(w, "解析JSON数据失败: "+err.Error(), http.StatusBadRequest)
		return
	}
	
	// 验证配置数据
	if newConfig.Enabled {
		if newConfig.Port <= 0 {
			newConfig.Port = 8081 // 默认端口
		}
		
		if newConfig.Port < 1024 {
			errorResponse(w, "端口号应大于1024", http.StatusBadRequest)
			return
		}
		
		if newConfig.BasePath == "" {
			errorResponse(w, "必须指定基础路径", http.StatusBadRequest)
			return
		}
		
		if newConfig.URLPath == "" {
			newConfig.URLPath = "/files" // 默认URL路径
		}
	}
	
	// 更新配置
	err = UpdateFileServerConfig(&newConfig)
	if err != nil {
		errorResponse(w, "更新配置失败: "+err.Error(), http.StatusInternalServerError)
		return
	}
	
	// 返回成功
	successResponse(w, "文件服务器配置已成功保存")
}

// 注册文件服务器API路由
func RegisterFileServerAPIRoutes(mux *http.ServeMux) {
	// 文件服务器配置API
	mux.HandleFunc("/api/fileserver/config", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			FileServerGetConfigHandler(w, r)
		case http.MethodPost:
			FileServerUpdateConfigHandler(w, r)
		default:
			http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
		}
	})
} 